package org.subatu.orm.core;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.stereotype.Service;
import org.subatu.orm.query.SqlWrapper;
import org.subatu.orm.service.QueryWrapper;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 基础Service实现类
 *
 * @param <T>
 */
@Service("SubatuBaseServiceImpl")
public class BaseServiceImpl<T> extends BaseMapperImpl<T> implements BaseService<T> {

    @Autowired
    private JdbcClient jdbcClient;

    public SqlWrapper<T> query() {
        // 为保证 sqlWrapper纯度,每次都是 new 最新的
        SqlWrapper sqlWrapper = new SqlWrapper(this);
        return sqlWrapper;
    }

    public QueryWrapper<T> lambda() {
        Type superClass = getClass().getGenericSuperclass();
        Type actualTypeArgument = ((ParameterizedType) superClass).getActualTypeArguments()[0];
        String typeName = actualTypeArgument.getTypeName();
        Class<T> clazz = null;
        try {
            clazz = (Class<T>) Class.forName(typeName);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return new QueryWrapper<T>(jdbcClient, clazz);
    }


}
